<template>
  <div :style="{ height: tableHeight + 'px', background: '#ffffff' }">
    <ContentWrap>
      <div class="routeHeader mb-5px">
        <div>
          <el-button
            @click="saveData"
            type="primary"
            v-hasPermi="['produce:production-prepare-packing:save']"
            v-if="type !== 'view' && type !== 'sendView'"
            >保存</el-button
          >
          <el-button
            @click="cancelData"
            type="primary"
            v-hasPermi="['produce:production-prepare-packing:cancel']"
            v-if="type == 'update'"
            >作废</el-button
          >
          <el-button
            @click="print"
            type="primary"
            v-hasPermi="['produce:production-prepare-packing:print']"
            v-if="type == 'view' || type == 'sendView'"
            >打印装箱单</el-button
          >
          <el-button @click="close">关闭</el-button>
        </div>
      </div>
    </ContentWrap>
    <ContentWrap>
      <div>基本信息</div>
      <el-form
        class="-mb-5px"
        :model="queryParam"
        :inline="true"
        label-width="110px"
        :rules="rules"
        ref="ruleFormRef"
      >
        <el-form-item label="清单编号" prop="prepareNumber">
          <div class="select-wrapper">
            <el-input
              v-model="queryParam.prepareNumber"
              readonly
              :disabled="type == 'view' || type == 'sendView'"
              class="!w-220px"
            />
            <span class="search-icon" @click="handQueryInventory()">
              <Icon icon="ep:search" />
            </span>
          </div>
        </el-form-item>
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="queryParam.orderNumber" disabled class="!w-220px" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="queryParam.customerName" class="!w-220px" disabled />
        </el-form-item>
        <el-form-item label="产品编号" prop="productNumber">
          <el-input v-model="queryParam.productNumber" class="!w-220px" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="queryParam.productName" class="!w-220px" disabled />
        </el-form-item>
        <el-form-item label="运达地点" prop="location">
          <el-input
            v-model="queryParam.location"
            class="!w-220px"
            :disabled="type == 'view' || type == 'sendView'"
          />
        </el-form-item>
        <el-form-item label="箱型尺寸" prop="boxSize">
          <el-input
            v-model="queryParam.boxSize"
            class="!w-220px"
            :disabled="type == 'view' || type == 'sendView'"
          />
        </el-form-item>
        <el-form-item label="日期" prop="locationTime">
          <el-input
            v-model="queryParam.locationTime"
            class="!w-220px"
            :disabled="type == 'view' || type == 'sendView'"
          />
        </el-form-item>
        <el-form-item label="箱子名称" prop="boxName">
          <el-input
            v-model="queryParam.boxName"
            class="!w-220px"
            :disabled="type == 'view' || type == 'sendView'"
          />
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <div class="btnWrap">
        <div>清单明细</div>
        <div>
          <el-button type="primary" v-if="!['view','sendView'].includes(type)" @click="chooseComponent()">选择部件</el-button>
        </div>
      </div>
      <el-table v-loading="loading" :data="list" border>
        <el-table-column type="index" width="55" label="序号" align="center" />
        <!-- 列定义 -->
        <!-- <el-table-column align="center" width="180">
          <template #header>
            <span>编号</span>
          </template>
          <template #default="scope"> {{ scope.row.productNumber }} </template>
        </el-table-column> -->
        <el-table-column align="center" width="180">
          <template #header>
            <span>部件编码</span>
          </template>
          <template #default="scope"> {{ scope.row.partNumber }} </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span>部件名称</span>
          </template>
          <template #default="scope"> {{ scope.row.partName }} </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span>部件规格</span>
          </template>
          <template #default="scope"> {{ scope.row.partSpecification }} </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span>图纸图号</span>
          </template>
          <template #default="scope">
            <el-button type="primary" link @click="jumpPdfFile(scope.row.partDrawingNumber)">{{
              scope.row.partDrawingNumber
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" width="180" v-if="route.query.type!=='view'">
          <template #header>
            <span>备货数量</span>
          </template>
          <template #default="scope"> {{ scope.row.prepareQuantity }} </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span>待发货数量</span>
          </template>
          <template #default="scope"> {{ scope.row.prepareRemaQuantity }} </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span>外形尺寸</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'prepareQuantityView'"
              name="prepareQuantityView"
              v-model="scope.row.overallDimension"
              placeholder="请输入外形尺寸"
              :disabled="type == 'view' || type == 'sendView'"
              class="!w-140px"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span style="color: red">*</span>
            <span>装箱数量</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'prepareQuantityView'"
              name="prepareQuantityView"
              v-model.number="scope.row.packingQuantity"
              placeholder="请输入装箱数量"
              :disabled="type == 'view' || type == 'sendView'"
              type="number"
              :min="0"
              :max="100"
              class="!w-140px"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span>单位</span>
          </template>
          <template #default="scope"> {{ scope.row.dictUnit }} </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span>单件质量(KG)</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'remark'"
              name="remark"
              v-model="scope.row.weight"
              :disabled="type == 'view' || type == 'sendView'"
              placeholder="请输入单件质量"
              type="number"
              :min="0"
              :max="100"
              class="!w-140px"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" width="180">
          <template #header>
            <span>总量 (KG)</span>
          </template>
          <template #default="scope">
            <el-input
              v-nextInput="'remark'"
              name="remark"
              v-model="scope.row.weightTotal"
              :disabled="type == 'view' || type == 'sendView'"
              placeholder="请输入单件质量"
              type="number"
              :min="0"
              :max="100"
              class="!w-140px"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="180">
          <template #default="scope">
            <el-input
              v-nextInput="'remark'"
              name="remark"
              v-model="scope.row.remark"
              :disabled="type == 'view' || type == 'sendView'"
              placeholder="请输入备注"
              type="number"
              :min="0"
              :max="100"
              class="!w-140px"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column label="入库类型" align="center" width="180">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.INCOMING_TYPE" :value="scope.row.dictIncomingType" />
          </template>
        </el-table-column> -->
        <el-table-column label="仓库名称" align="center" width="180">
          <template #default="scope"> {{ scope.row.warehouseName }} </template>
        </el-table-column>
        <el-table-column label="操作" align="left" header-align="left"  fixed="right">
        <template #default="scope">
          <el-button
            v-if="route.query.type === 'create' || route.query.type === 'update' "
            link
            type="danger"
            @click="delRow(scope.$index)"
            v-hasPermi="['produce:production-prepare-packing:del']"
          >
            移除行
          </el-button>
        </template>
      </el-table-column>
      </el-table>
    </ContentWrap>
    <!-- 选择清单 -->
    <selectInventory ref="formRefInventory" @success="getInventory" />
    <!-- 选择部件 -->
    <SelectComponent ref="formRefComponent" @success="addData" :componentList="list" />
    <!-- 打印 -->
    <div v-show="false" id="printData">
      <Print :info="queryParam" :list="dataList" :dataListLength="dataListLength" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { jumpPdfFile } from '@/utils/formCreate'
import { useRoute } from 'vue-router'
// import { DICT_TYPE } from '@/utils/dict'
import * as ProductionPreparePackingApi from '@/api/produce/productManagement/productionPreparePacking'
import { useTagsViewStore } from '@/store/modules/tagsView'
import selectInventory from './selectInventory.vue'
import SelectComponent from './selectComponent.vue'
import Print from './print.vue'
const tagsViewStore = useTagsViewStore()
const routes = useRouter() // 路由
const route = useRoute()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const queryParam = ref({
  orderNumber: undefined,
  prepareNumber: undefined,
  dictOrderType: undefined,
  customerCode: undefined,
  customerName: undefined,
  productNumber: undefined,
  productName: undefined,
  productStandard: undefined,
  inventoryNumber: undefined,
  productionPreparePackingDetailCreateReqVOS: []
})
const { push } = useRouter()
const loading = ref(true)
const list = ref<any>([])
// const formLoading = ref(false)
const formRefInventory = ref()
const handQueryInventory = () => {
  if (type.value == 'view' || type.value == 'sendView') return
  formRefInventory.value.open(queryParam.value.orderNumber, queryParam.value.productNumber)
}
const formRefComponent = ref()
const ruleFormRef = ref()
const rules = reactive({
  prepareNumber: [{ required: true, message: '请选择清单编号', trigger: 'blur' }],
  location: [{ required: true, message: '请输入运达地点', trigger: 'blur' }],
  boxSize: [{ required: true, message: '请输入箱型尺寸', trigger: 'blur' }],
  locationTime: [{ required: true, message: '请输入日期', trigger: 'blur' }]
})

const chooseComponent = () => {
  if (type.value == 'view' || type.value == 'sendView') return
  if (
    queryParam.value.orderNumber != undefined &&
    queryParam.value.orderNumber != null &&
    queryParam.value.productNumber != null &&
    queryParam.value.productNumber != undefined
  ) {
    formRefComponent.value.open(undefined, undefined, queryParam.value.prepareId)
  } else {
    message.warning('订单号和产品编号都不能为空')
  }
}
let isSelectComponent = ref(false) // 是否选中部件
const addData = async (data) => {
  console.log(data.list)
  for (let i = 0; i < data.list.length; i++) {
    const newRow = {
      prepareId: data.list[i].prepareId,
      partNumber: data.list[i].partNumber,
      partName: data.list[i].partName,
      partDrawingNumber: data.list[i].partDrawingNumber,
      partSpecification: data.list[i].partSpecification,
      incomingQuantity: data.list[i].incomingQuantity,
      prepareQuantity: data.list[i].prepareQuantity,
      dictUnit: data.list[i].dictUnit,
      dictIncomingType: data.list[i].dictIncomingType,
      warehouseName: data.list[i].warehouseName,
      prepareRemaQuantity: data.list[i].prepareRemaQuantity
    }
    list.value.push(newRow)
    isSelectComponent.value = true
  }
}
const getList = async () => {
  loading.value = true
  try {
    // 请求数据的逻辑
  } finally {
    loading.value = false
  }
}

//获取清单数据
const getInventory = (data) => {
  queryParam.value.prepareNumber = data.list[0].prepareNumber
  queryParam.value.orderNumber = data.list[0].orderNumber
  queryParam.value.customerName = data.list[0].customerName
  queryParam.value.productNumber = data.list[0].productNumber
  queryParam.value.productName = data.list[0].productName
  queryParam.value.prepareId = data.list[0].id
  list.value = []
}

//必填校验
const check = async () => {
  let data = await list.value
  if (data.length) {
    for (let i = 0; i < data.length; i++) {
      if (!data[i].packingQuantity) {
        message.warning(t('装箱数量不能为空'))
        return false
      }
      console.log('data123', data)
      if (data[i].packingQuantity > data[i].prepareRemaQuantity) {
        message.warning(t('装箱数量不能大于备货剩余数量'))
        return false
      }
    }
  } else {
    message.warning(t('请选择部件'))
    return false
  }
  return true
}

const delRow = (index: number) => {
    list.value.splice(index, 1)
  }

/**保存 */
const saveData = async () => {
  let validateStatus = await ruleFormRef.value.validate()
  if (!validateStatus) return
  const isFlag = await check()
  if (isFlag) {
    queryParam.value.productionPreparePackingDetailCreateReqVOS = list.value
    if (type.value === 'create') {
      await ProductionPreparePackingApi.createProductionPreparePacking(queryParam.value)
      message.success(t('保存成功'))
      tagsViewStore.delView(routes.currentRoute.value)
      push('/produce/produce/productManagement/productionPreparePacking')
    } else {
      await ProductionPreparePackingApi.updateProductionPreparePacking(queryParam.value)
      message.success(t('保存成功'))
      tagsViewStore.delView(routes.currentRoute.value)
      push('/produce/produce/productManagement/productionPreparePacking')
    }
  }
}

/**作废 */
const cancelData = async () => {
  queryParam.value.productionPreparePackingDetailCreateReqVOS = list.value
  await ProductionPreparePackingApi.cancelProductionPreparePacking(queryParam.value)
  message.success(t('已作废'))
  tagsViewStore.delView(routes.currentRoute.value)
  push('/produce/produce/productManagement/productionPreparePacking')
}
/**关闭 */
const close = () => {
  if (route.query.type == 'sendView') {
    tagsViewStore.delView(routes.currentRoute.value)
    push({
      path: '/produce/produce/productManagement/productionPrepareSendEdit',
      query: {
        type: 'view',
        id: route.query.sendId
      }
    })
  } else {
    tagsViewStore.delView(routes.currentRoute.value)
    push('/produce/produce/productManagement/productionPreparePacking')
  }
}

// 打印领料单
const print = () => {
  // 新建窗口
  let winName, head, bdHtml
  winName = window.open('', '_blank', '') // 新窗口
  head = '<link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />'
  const tabStyle = `
  <style>
  table {
    border-collapse: collapse;
    width: 100%;
  }
  th, td {
    text-align: center;
    padding: 8px;
    border: 1px solid black;
  }
  </style>
  `
  head += tabStyle
  bdHtml = window.document.querySelector('#printData').innerHTML
  winName.document.head.innerHTML = head
  winName.document.body.innerHTML = bdHtml
  winName.focus() //聚焦保证页面正常
  setTimeout(() => {
    winName.print()
  }, 500)
}

let type = ref() // 当前操作状态
let id = ref()
let dataList = ref([])
let dataListLength = ref()
// 初始化
const contentHeight = ref(0)
const tableHeight = ref(0)
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 127
  tableHeight.value = document.body.clientHeight - 130
  type.value = route.query.type
  id.value = route.query.id
  console.log(type.value,'type.value')
  if (type.value != 'create') {
    queryParam.value = await ProductionPreparePackingApi.getProductionPreparePacking(id.value)
    list.value = queryParam.value.productionPreparePackingDetailRespVOS
    dataList.value = []
    dataList.value.push(list.value)
    dataListLength.value = dataList.value[0].length
  }
  // if (id.value!= 'undefined') {
  //   getDetail(id.value)
  // }
  await getList()
})
</script>
<style lang="scss" scoped>
.tableView {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
    cursor: default;

    .el-input__inner {
      cursor: default !important;
      text-align: center;
    }
  }
}

.btnWrap {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.el-table .custom-header::before {
  content: '*';
  color: red;
  margin-right: 4px; /* 根据需要调整小红星与字段的位置 */
}

.dropdown-width {
  width: 50px !important;
}

:deep(.el-form .el-input, .el-form .el-input__wrapper, .el-form .el-textarea) {
  width: 100% !important;
}

.select-wrapper {
  display: flex;
  align-items: center;
}

.search-icon {
  margin-left: -24px; /* 这里的 -24px 是根据 Icon 的宽度进行调整的 */
  cursor: pointer;
  margin-top: 5px;
}
</style>
